﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace LINQAmazonProvider
{
    public class RestDataAccess
    {
        private string _url;
        private string _result;

        public RestDataAccess(string url)
        {
            _url = url;
        }

        public void PerformRestRequest()
        {

            // Initialize a new instance of the Uri class with the URI that points
            // to the location of the XML file that you want to load.
            Uri location = new Uri(_url, UriKind.Absolute);

            // Create an HttpWebRequest object to the desired URI. 
            WebRequest request = HttpWebRequest.Create(location);

            // Start the asynchronous request.
            request.BeginGetResponse(new AsyncCallback(OpenStreamCompleted), request);

        }

        private void OpenStreamCompleted(IAsyncResult ar)
        {
            HttpWebRequest request = ar.AsyncState as HttpWebRequest;
            WebResponse response = request.EndGetResponse(ar);

            // Read the response into a Stream object.
            Stream responseStream = response.GetResponseStream();

            // Create a new StreamReader instance using the specified Stream object.
            using (StreamReader streamreader = new StreamReader(responseStream))
            {
                _result = streamreader.ReadToEnd();
            }

            OnRestRequestCompleted(new RestRequestCompletedEventArgs(_result));
        }

        public delegate void RestRequestCompletedHandler(object sender, RestRequestCompletedEventArgs e);

        public event RestRequestCompletedHandler RestRequestCompleted;

        // Invoke the Changed event; called whenever list changes
        protected virtual void OnRestRequestCompleted(RestRequestCompletedEventArgs e)
        {
            if (RestRequestCompleted != null)
                RestRequestCompleted(this, e);
        }

    }
    public class RestRequestCompletedEventArgs
    {
        string _result;

        public RestRequestCompletedEventArgs(string result)
        {
            _result = result;
        }

        public string Result
        {
            get
            {
                return _result;
            }
        }
    }
}
